<template>
  <div>
    <el-form ref="editProjectForm" :model="formItem" :rules="rules" label-width="100px" size="mini">
      <el-row :gutter="40">
        <el-col :span="8">
          <el-form-item label="巡检对象类型" required prop="projectType">
            <el-select v-model="formItem.projectType" class="select_input" placeholder="请选择资产状态">
              <el-option v-for="(item) in projectTypes" :key="item.code" :label="item.text" :value="item.code" @click.native="clickProjectType(item)" />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col v-if="formItem.projectType==='system'" :span="8">
          <el-form-item label="系统" required prop="locationCode">
            <treeselect
              v-model="formItem.locationCode"
              :multiple="false"
              label-key="name"
              :options="availableSystems"
              placeholder="请选择系统"
              @select="selcetSystem"
              @input="inputSystem"
            />
          </el-form-item>
        </el-col>
        <el-col v-else :span="8">
          <el-form-item label="位置" required prop="locationCode">
            <treeselect
              v-model="formItem.locationCode"
              :multiple="false"
              :options="availableLocations"
              label-key="name"
              placeholder="请选择位置"
              @select="selcetLocation"
              @input="inputLocation"
            />
          </el-form-item>
        </el-col>
        <el-col v-if="formItem.projectType==='asset'" :span="8">
          <el-form-item label="类型" required prop="typeCode">
            <treeselect
              v-model="formItem.typeCode"
              :multiple="false"
              :options="availableTypes"
              label-key="name"
              :disable-branch-nodes="true"
              placeholder="请选择类型"
              @select="selcetType"
              @input="inputType"
            />
          </el-form-item>
        </el-col>

        <el-col v-if="formItem.projectType!=='location'" :span="24">
          <el-form-item label="巡检对象" required title="请先选择位置和类型">
            <!-- <el-input placeholder="请输入巡检对象" :disabled="!formItem.locationCode" @focus="handleSelect">
              <div slot="prefix">
                <el-tag v-for="tag in formItem.projectConcrete" :key="tag.concreteCode" size="mini" closable type="success" @close="removeTag(tag)">{{ tag.concreteName }}</el-tag>
              </div>
            </el-input> -->

            <el-select v-model="formItem.projectConcreteCodes" multiple :loading="loading" class="select_input" placeholder="请选择待巡检资产" @remove-tag="removeSelectTag">
              <el-option v-for="(item) in projectConcretes" :key="item.code" :label="item.name" :value="item.code" @click.native="clickOption(item)" />
            </el-select>
          </el-form-item>

        </el-col>
      </el-row>
      <el-row :gutter="40">
        <el-col :span="24">
          <div class="form-info-title">
            <i class="el-icon-document" /><span>巡检项</span>
            <div>
              <el-button type="primary" size="mini" icon="el-icon-plus" @click="addInspecitonItem">增加</el-button>
              <el-button type="primary" size="mini" icon="el-icon-document-copy" @click="copyInspecitonItem">复制</el-button>
            </div>
          </div>
        </el-col>
        <el-col v-for="(item,index) in formItem.inspectionItem" :key="index" :span="22" :offset="1">
          <el-card shadow="never">
            <el-col :span="8">
              <el-form-item label="名称" required>
                <el-input v-model="item.name" placeholder="请输入名称" :maxlength="255" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="值类型">
                <el-select v-model="item.valueType" class="select_input" placeholder="请选择值类型">
                  <el-option v-for="(it) in valueTypes" :key="it.code" :label="it.text" :value="it.code" />
                </el-select>
              </el-form-item>
            </el-col>

            <div v-if="item.valueType=='number'">
              <el-col :span="8">
                <el-form-item label="单位">
                  <el-input v-model="item.unit" type="text" placeholder="请输入单位" :max="255" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="告警值下限" required>
                  <el-input-number v-model="item.alarmDown" :precision="3" :step="1" :max="100000000" label="请输入告警值下限" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="预警值下限" required>
                  <el-input-number v-model="item.earlyWarningDown" :precision="3" :step="1" :max="100000000" label="请输入预警值下限" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="预警值上限" required>
                  <el-input-number v-model="item.earlyWarningUpper" :precision="3" :step="1" :max="100000000" label="请输入预警值上限" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="告警值上限" required>
                  <el-input-number v-model="item.alarmUpper" :precision="3" :step="1" :max="100000000" label="请输入告警值上限" />
                </el-form-item>
              </el-col>
            </div>
            <div v-else>
              <el-col :span="8">
                <el-form-item label="预警值范围" required>
                  <el-input v-model="item.earlyWarning" placeholder="请输入约束值，多个值以逗号分隔" />
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="告警值范围" required>
                  <el-input v-model="item.alarm" placeholder="请输入约束值，多个值以逗号分隔" />
                </el-form-item>
              </el-col>
            </div>
            <el-col :span="8">
              <el-form-item label="排序">
                <el-input-number v-model="item.sort" :min="0" :step="1" :precision="0" :max="10000" label="描述文字" />
              </el-form-item>
            </el-col>
            <el-col :span="1" :offset="6">
              <el-button type="danger" size="mini" icon="el-icon-minus" @click="handleRemove(index)" />
            </el-col>
            <!-- <el-form-item label="类别" prop="type">
                <el-input v-model="formItem.type" type="text" placeholder="请输入类别" />
              </el-form-item> -->
          </el-card>
        </el-col>
      </el-row>
    </el-form>
    <!-- <SelectDialog title="选择维护对象" width="60%" :append-to-body="true" :show="assetDialogFormVisible" @on-ok="selectOk" @on-cancel="selectCancel">
      <instancesTable v-if="assetDialogFormVisible" ref="instancesTable" :for-selection="true" :model-code="formItem.typeCode" :location-code="locationCode" />
    </SelectDialog> -->
    <SelectDialog title="复制巡检项" :append-to-body="true" :show="showItem" @on-ok="showItemOk" @on-cancel="showItemCancel">
      <projectItem v-if="showItem" ref="itemProject" :type="formItem.typeCode" :for-selection="true" :multiple-selected="true" />
    </SelectDialog>
  </div>
</template>

<script>
import SelectDialog from '@neu/biz-core/components/SelectDialog'
import projectItem from '@neu/dcom-ui/views/inspection/inspectionItem/tables'
import treeselect from '@neu/biz-core/components/TreeSelect'
import { findByDictionaryType } from '@neu/dcom-ui/api/dictionary'
import * as cmdbApi from '@neu/dcom-ui/api/cmdb'
// import instancesTable from '@neu/dcom-ui/views/instances'
// 定义一个表单原始项
const formItem = {
  /** 巡检对象类型 */
  projectType: 'asset',
  // 位置编码/系统编码
  locationCode: null,
  locationName: null,
  // 类型编码
  typeCode: null,
  typeName: null,
  // 待巡检资产
  projectConcrete: [],
  /** 待巡检资产codes */
  projectConcreteCodes: [],
  // 巡检项
  inspectionItem: []
}
export default {
  name: 'InspectionRuleProjectEdit',
  components: {
    treeselect,
    // instancesTable,
    SelectDialog,
    projectItem
  },
  props: {
    // 根据id可判断是新建还是更新
    id: {
      required: false,
      type: Number,
      default: -1
    },
    initData: {
      required: false,
      type: Object,
      default: formItem
    }
  },
  data() {
    return {
      // 是否显示巡检项
      showItem: false,
      /** 传给组件的值 */
      locationCode: null,
      loading: false,
      assetDialogFormVisible: false,
      /** 巡检对象类型： 资产、位置、系统 */
      projectTypes: [],
      availableLocations: [],
      availableSystems: [],
      availableTypes: [],
      inspectionTypes: [],
      valueTypes: [],
      /** 待选资产 */
      projectConcretes: [],
      // 编辑的表单内容
      formItem: JSON.parse(JSON.stringify(this.initData)),
      // 表单验证规则
      rules: {
        projectType: [{ required: true, message: '巡检对象类型不能为空', trigger: 'blur' }],
        locationCode: [{ required: true, message: '不能为空', trigger: 'blur' }],
        typeCode: [{ required: true, message: '类型不能为空', trigger: 'blur' }],
        system: [{ required: true, message: '系统不能为空', trigger: 'change' }],
        name: [{ required: true, message: '巡检项名称不能为空', trigger: 'change' }],
        valueType: [{ required: true, message: '值类型不能为空', trigger: 'blur' }],
        earlyWarning: [{ required: true, message: '预警范围不能为空', trigger: 'blur' }],
        alarm: [{ required: true, message: '告警范围不能为空', trigger: 'blur' }]
        // jobDesc: [{ required: true, message: '描述不能为空', trigger: 'blur' }]
      },
      modal: true,
      normalizerProject(node) {
        if (node.children && !node.children.length) {
          delete node.children
        }
        return {
          id: node.code,
          label: node.name,
          children: node.children
        }
      }
    }
  },
  watch: {
    // 'initData': {
    //   immediate: true,
    //   deep: true,
    //   handler(newVal, oldVal) {
    //     console.log('watcher')
    //     if (newVal && newVal.typeCode && newVal.locationCode) {
    //       if (newVal.projectConcrete && newVal.projectConcrete.length > 0) {
    //         newVal.projectConcreteCodes = newVal.projectConcrete.map(project => project.concreteCode)
    //       }
    //       this.formItem.projectConcreteCodes = JSON.parse(JSON.stringify(newVal.projectConcreteCodes))
    //       this.getAsset()
    //     }
    //   }
    // }
    'formItem.locationCode': {
      immediate: true,
      handler(newVal, oldVal) {
        if (this.formItem.projectType === 'asset') {
          this.getAsset()
        }
        if (this.formItem.projectType === 'system') {
          this.getBusinessAsset()
        }
      }
    },
    'formItem.typeCode': {
      immediate: true,
      handler(newVal, oldVal) {
        this.getAsset()
      }
    }
  },
  created() {
    findByDictionaryType('inspectionValueType').then(response => {
      this.valueTypes = response.data
    })
    findByDictionaryType('projectType').then(response => {
      this.projectTypes = response.data
    })
    cmdbApi.tree().then(res => {
      this.availableTypes = res.data
    })
    cmdbApi.locationTree().then(res => {
      this.availableLocations = res.data
    })
    cmdbApi.list().then(res => {
      this.availableSystems = res.data
    })
  },
  methods: {
    // 保存操作，返回promise，后续处理交由调用者处理
    save() {
      this.$refs.editProjectForm.validate((valid) => {
        if (valid) {
          if (this.formItem.projectType !== 'location' && this.formItem.projectConcrete.length === 0) {
            return this.$message({
              showClose: true,
              message: '未设置巡检对象',
              type: 'error'
            })
          }
          if (this.formItem.inspectionItem.length === 0) {
            return this.$message({
              showClose: true,
              message: '未设置巡检项',
              type: 'error'
            })
          }
          const names = this.formItem.inspectionItem.map(item => item.name)
          for (const item of names) {
            const start = names.indexOf(item)
            const end = names.lastIndexOf(item)
            if (start !== end) {
              return this.$message({
                showClose: true,
                message: '第' + (start + 1) + '条巡检项，' + '第' + (end + 1) + '条巡检项，名称不能重复',
                type: 'error'
              })
            }
          }
          // 巡检项校验
          for (let i = 0; i < this.formItem.inspectionItem.length; i++) {
            const obj = this.formItem.inspectionItem[i]
            if (!obj.name) {
              return this.$message({
                showClose: true,
                message: '第' + (i + 1) + '条巡检项，巡检项名称不能为空',
                type: 'error'
              })
            }
            if (obj.valueType === 'string') {
              if (!obj.alarm) {
                return this.$message({
                  showClose: true,
                  message: '第' + (i + 1) + '条巡检项，告警值范围不能为空',
                  type: 'error'
                })
              }
              if (!obj.earlyWarning) {
                return this.$message({
                  showClose: true,
                  message: '第' + (i + 1) + '条巡检项，预警值范围不能为空',
                  type: 'error'
                })
              }
            } else {
              if (obj.alarmDown !== undefined && obj.earlyWarningDown !== undefined && obj.earlyWarningUpper !== undefined && obj.alarmUpper !== undefined && obj.alarmDown < obj.earlyWarningDown && obj.earlyWarningDown < obj.earlyWarningUpper && obj.earlyWarningUpper < obj.alarmUpper) {
                //
              } else {
                return this.$message({
                  showClose: true,
                  message: '第' + (i + 1) + '条巡检项，配置规则应满足：告警下限值<预警下限值<预警上限值<告警上限值',
                  type: 'error'
                })
              }
            }
          }
          this.$emit('saveData', this.formItem)
        } else {
          this.$emit('saveData', null)
        }
      })
    },
    reset() {
      this.$refs.editProjectForm.resetFields()
      this.formItem = { ...formItem }
    },
    // handleRemove(item) {
    //   this.formItem.inspectionItem = this.formItem.inspectionItem.filter(m => (m.id !== item.id))
    // },
    handleRemove(index) {
      this.formItem.inspectionItem.splice(index, 1)
    },
    addInspecitonItem() {
      const obj = {
        // id: this.formItem.inspectionItem.length,
        name: '',
        valueType: 'number',
        unit: '',
        earlyWarningDown: '',
        earlyWarningUpper: '',
        alarmDown: '',
        alarmUpper: '',
        earlyWarning: '',
        alarm: '',
        sort: '',
        type: ''
      }
      this.formItem.inspectionItem.push(obj)
    },
    handleSelect() {
      this.assetDialogFormVisible = true
    },

    selectOk() {
      const self = this
      var assets = this.$refs.instancesTable.selections
      var currentUserIds = self.formItem.projectConcrete.map(project => project.concreteCode)
      var difference = assets.filter(t => {
        return !currentUserIds.includes(t.code)
      })
      difference.forEach(t => {
        const asset = { concreteCode: t.code + '', concreteName: t.name }
        self.formItem.projectConcrete.push(asset)
      })

      this.assetDialogFormVisible = false
    },
    selectCancel() {
      this.assetDialogFormVisible = false
    },
    removeTag(tag) {
      this.formItem.projectConcrete.splice(this.formItem.projectConcrete.indexOf(tag), 1)
    },
    /** 系统赋值 */
    selcetSystem(value) {
      this.formItem.locationName = value.name
      this.formItem.locationCode = value.code
      this.resetProjectConcrete()
      // 当前巡检对象类型是系统，赋值类型字段
      this.formItem.typeCode = value.code
      this.formItem.typeName = value.name
    },
    inputSystem(value) {
      if (value === undefined) {
        this.formItem.locationName = ''
        this.resetProjectConcrete()

        // 当前巡检对象类型是系统，清空类型字段和巡检对象字段
        this.formItem.typeCode = ''
        this.formItem.typeName = ''
      }
    },
    /** 位置赋值 */
    selcetLocation(value) {
      // this.formItem.locationName = value.name
      this.formItem.locationCode = value.code
      this.getSelectedItem(value.code, this.availableLocations)
      this.resetProjectConcrete()
      // 当前巡检对象类型是位置，赋值类型字段和巡检对象字段
      if (this.formItem.projectType === 'location') {
        this.formItem.typeCode = 'location'
        this.formItem.typeName = '位置'
        const obj = { concreteCode: this.formItem.locationCode + '', concreteName: this.formItem.locationName }
        this.formItem.projectConcrete.push(obj)
      }
    },
    inputLocation(value) {
      if (value === undefined) {
        this.formItem.locationName = ''
        this.resetProjectConcrete()
        if (this.formItem.projectType === 'location') {
          this.formItem.typeCode = ''
          this.formItem.typeName = ''
        // const obj = { concreteCode: this.formItem.locationCode + '', concreteName: this.formItem.locationName }
        // this.formItem.projectConcrete = []
        }
      }
      // this.getAsset()
      // 当前巡检对象类型是位置，清空类型字段和巡检对象字段
    },
    getSelectedItem(code, data, name) {
      for (const item of data) {
        // 在根节点找到对应选项
        if (!name && item.code === code) {
          this.formItem.locationName = item.name
          break
        } else if (!name && item.children) { // 根节点未找到继续递归查找
          this.formItem.locationName = item.name
          this.getSelectedItem(code, item.children, this.formItem.locationName)
          break
        }

        // 在子节点找到对应选项
        if (name && item.code === code) {
          this.formItem.locationName = name + '->' + item.name
          break
        } else if (name && item.children) { // 当前子节点未找到继续递归向下查找
          this.formItem.locationName = name + '->' + item.name
          this.getSelectedItem(code, item.children, this.formItem.locationName)
          break
        }
      }
    },
    /** 类型 */
    selcetType(value) {
      this.formItem.typeName = value.name
      this.formItem.typeCode = value.code
      this.resetProjectConcrete()
    },
    inputType(value) {
      if (value === undefined) {
        this.formItem.typeName = ''
        this.resetProjectConcrete()
      }
    },
    resetProjectConcrete() {
      this.formItem.projectConcrete = []
      this.projectConcretes = []
      this.formItem.projectConcreteCodes = []
    },
    getAsset() {
      if (this.formItem.projectType === 'asset' && this.formItem.locationCode && this.formItem.typeCode) {
        this.loading = true
        const params = {
          's_location': this.formItem.locationCode
        }
        cmdbApi.listByScheam(params, this.formItem.typeCode).then(res => {
          this.projectConcretes = res.data
          this.loading = false
        })
      }
    },
    getBusinessAsset() {
      if (this.formItem.projectType === 'system') {
        cmdbApi.businessDetail(this.formItem.locationCode).then(res => {
          this.projectConcretes = res.data.instances
        })
      }
    },
    clickOption(item) {
      if (this.formItem.projectConcreteCodes.includes(item.code)) {
        const obj = { concreteCode: item.code + '', concreteName: item.name }
        this.formItem.projectConcrete.push(obj)
      } else {
        this.formItem.projectConcrete = this.formItem.projectConcrete.filter(t => {
          return t.concreteCode !== item.code
        })
      }
      // console.log(this.formItem.projectConcrete)
    },
    removeSelectTag(itemCode) {
      this.formItem.projectConcrete = this.formItem.projectConcrete.filter(t => {
        return t.concreteCode !== itemCode
      })
      // console.log(this.formItem.projectConcrete)
    },
    /** 确认巡检项**/
    showItemOk() {
      this.showItem = false
      var items = this.$refs.itemProject.selections
      var currentKeys = this.formItem.inspectionItem.map(t => t.key)
      var difference = items.filter(t => {
        return !currentKeys.includes(t.id)
      })
      difference.forEach(i => {
        const obj = {
          key: i.id,
          name: i.name,
          valueType: i.valueType,
          unit: i.unit,
          earlyWarningDown: i.earlyWarningDown,
          earlyWarningUpper: i.earlyWarningUpper,
          alarmDown: i.alarmDown,
          alarmUpper: i.alarmUpper,
          earlyWarning: i.earlyWarning,
          alarm: i.alarm,
          sort: i.sort,
          type: i.type
        }
        this.formItem.inspectionItem.push(obj)
      })
    },
    /** 取消巡检项**/
    showItemCancel() {
      this.showItem = false
    },
    copyInspecitonItem() {
      this.showItem = true
    },
    clickProjectType(item) {
      this.formItem.locationCode = null
      this.formItem.locationName = ''
      this.formItem.typeCode = null
      this.formItem.typeName = ''
      this.resetProjectConcrete()
    }
  }
}
</script>
